using System.Collections.Generic;
using QFramework;
using UnityEngine;
using UnityEngine.UI;

public class GiftManager : MonoBehaviour
{
    public Transform canvas; // 礼物特效的父节点
    public StudentManager studentManager; // 学生管理器引用
    
    // 礼物播放位置类型枚举
    public enum GiftPlayMode
    {
        OnCanvas,       // 在画布上播放
        OnStudent,      // 直接在学生节点上播放
        Challenge       // 挑战类型（需要两个头像）
    }

    public enum AnimaName // 礼物名称映射规则
    {
        DianZan = 0,
        StudentSpeak = 1,
        YanHua = 2,
        YouCome = 3,
        TeacherSpeak = 4,
        JiFenFanBei = 5,
        ChiTiZhengQue = 6,
        TiaoZhanNo1 = 7,

        //班级赛独有
        QingZhuLiHua = 8,
         JianShaoCuoWu = 9,
         QuanBanZhengQue = 10,
        ClassJiFenFanBei = 11,
         JueDiFanJi = 12
    }
    
    // 礼物路径映射规则
    private Dictionary<AnimaName, string> giftPathMapping = new Dictionary<AnimaName, string>()
    {
        //新动画OK - 班级赛个人赛复用
        { AnimaName.DianZan, "Gifts/DianZan" },
        //新动画OK - - 班级赛个人赛复用
        { AnimaName.YanHua, "Gifts/GiftYanHua" },
        //新动画OK - 班级赛个人赛复用
        { AnimaName.YouCome, "Gifts/GiftYouCome" },
         //新动画OK - 班级赛个人赛复用
        {AnimaName.JiFenFanBei, "Gifts/GiftCoinDown" },
        {AnimaName.ClassJiFenFanBei, "Gifts/GiftCoinDown" },
        
         //新动画OK-个人赛独有
        { AnimaName.TiaoZhanNo1, "Gifts/GiftChallengeNo1" },
         //新动画OK-个人赛独有
        { AnimaName.ChiTiZhengQue, "Gifts/GiftPersonalRight" },

        //班级赛独有
        { AnimaName.QingZhuLiHua, "Gifts/GiftLiHua" },
         //班级赛独有
        { AnimaName.JianShaoCuoWu, "Gifts/GiftReduceWrong" },
         //班级赛独有
        { AnimaName.QuanBanZhengQue, "Gifts/GiftAllRight" },
        // 班级赛独有
        { AnimaName.JueDiFanJi, "Gifts/GiftFanJi" },
    };
    
    // 礼物播放位置类型映射
    private Dictionary<AnimaName, GiftPlayMode> giftPlayModeMapping = new Dictionary<AnimaName, GiftPlayMode>()
    {
        { AnimaName.DianZan, GiftPlayMode.OnStudent },   // 点赞特效直接在学生节点上播放
        { AnimaName.YanHua, GiftPlayMode.OnCanvas },
        { AnimaName.YouCome, GiftPlayMode.OnCanvas },
        { AnimaName.JiFenFanBei, GiftPlayMode.OnCanvas },
        { AnimaName.ClassJiFenFanBei, GiftPlayMode.OnCanvas },
        { AnimaName.JueDiFanJi, GiftPlayMode.OnCanvas },
        { AnimaName.ChiTiZhengQue, GiftPlayMode.OnCanvas },
        { AnimaName.QingZhuLiHua, GiftPlayMode.OnCanvas },
        { AnimaName.TiaoZhanNo1, GiftPlayMode.Challenge },   // 挑战第一名，需要两个头像
        { AnimaName.JianShaoCuoWu, GiftPlayMode.OnCanvas },
        { AnimaName.QuanBanZhengQue, GiftPlayMode.OnCanvas },
    };
    
    // 礼物头像显示配置（是否在礼物中显示用户头像） 基本上都显示，可以删掉
    private Dictionary<AnimaName, bool> giftShowAvatarMapping = new Dictionary<AnimaName, bool>()
    {
        { AnimaName.DianZan, false },   // 点赞特效直接在学生节点上播放
        { AnimaName.YanHua, true },
        { AnimaName.YouCome, true },
        { AnimaName.JiFenFanBei, true },
        { AnimaName.ClassJiFenFanBei,true },
        { AnimaName.JueDiFanJi, true },
        { AnimaName.ChiTiZhengQue, true},
        { AnimaName.QingZhuLiHua, true },
        { AnimaName.TiaoZhanNo1, true },   // 挑战第一名，需要两个头像
        { AnimaName.JianShaoCuoWu, true },
        { AnimaName.QuanBanZhengQue, true },
    };
    
    // 礼物中头像的路径（相对于礼物预制体）
    private Dictionary<AnimaName, string> giftAvatarPathMapping = new Dictionary<AnimaName, string>()
    {
        { AnimaName.YanHua, "sp/Avatar" },
        { AnimaName.YouCome, "sp/Avatar" },
        { AnimaName.JiFenFanBei, "sp/Avatar" },
        { AnimaName.ClassJiFenFanBei,"sp/Avatar" },
        { AnimaName.JueDiFanJi, "sp/Avatar" },
        { AnimaName.ChiTiZhengQue, "sp/Avatar"},
        { AnimaName.QingZhuLiHua, "sp/Avatar" },
        { AnimaName.TiaoZhanNo1, "sp/Avatar1" },   // 挑战第一名，需要两个头像
        { AnimaName.JianShaoCuoWu, "sp/Avatar" },
        { AnimaName.QuanBanZhengQue, "sp/Avatar" },
    };
    
    // Start is called before the first frame update
    void Start()
    {
        // 初始化
        if (canvas == null)
        {
            // 如果没有指定canvas，则尝试查找
            canvas = GameObject.Find("Canvas")?.transform;
            if (canvas == null)
            {
                UnityEngine.Debug.LogError("GiftManager: Canvas not assigned or found!");
            }
        }
        
        // 如果没有指定StudentManager，则尝试查找
        if (studentManager == null)
        {
            studentManager = FindObjectOfType<StudentManager>();
            if (studentManager == null)
            {
                UnityEngine.Debug.LogWarning("GiftManager: StudentManager not assigned or found!");
            }
        }

        StringEventSystem.Global.Register(EventID.PlayGiftAnimation, (object[] args) =>
        {
           if (args.Length >= 2 && args[0] is AnimaName animaName && args[1] is GameObject student)
            {
                Debug.Log($"收到礼物: {animaName}");
                PlayGiftEffect(animaName, student);
            }

        }).UnRegisterWhenGameObjectDestroyed(gameObject);
    }
    
    
    private void PlayGiftEffect(AnimaName animaName,GameObject student = null)
    {
        Debug.Log($"PlayGiftEffect: {animaName}");
        if (!giftPathMapping.ContainsKey(animaName))
        {
            UnityEngine.Debug.LogWarning($"GiftManager: No gift mapping for key {animaName}");
            return;
        }
        
        // 获取礼物播放模式
        GiftPlayMode playMode = GiftPlayMode.OnCanvas;
        if (giftPlayModeMapping.ContainsKey(animaName))
        {
            playMode = giftPlayModeMapping[animaName];
        }
        
        // 根据播放模式处理礼物特效
        switch (playMode)
        {
            case GiftPlayMode.OnStudent:
                PlayGiftOnStudent(animaName,student);
                break;
            case GiftPlayMode.Challenge:
                PlayChallengeGift(animaName,student);
                break;
            default:
                PlayGiftOnCanvas(animaName,student);
                break;
        }
    }
    
    // 在Canvas上播放礼物特效
    private void PlayGiftOnCanvas(AnimaName animaName,GameObject sd = null)
    {
        string giftPath = giftPathMapping[animaName];
        GameObject giftPrefab = Resources.Load<GameObject>(giftPath);
        
        if (giftPrefab == null)
        {
            UnityEngine.Debug.LogError($"GiftManager: Failed to load gift prefab at path {giftPath}");
            return;
        }
        
        // 实例化礼物预制体
        GameObject giftInstance = Instantiate(giftPrefab, canvas);
        
        // 设置位置（根据需要调整）
        giftInstance.transform.localPosition = Vector3.zero;
        
        // 如果配置为显示头像，且StudentManager可用，则设置随机用户头像
        if (giftShowAvatarMapping.ContainsKey(animaName) && giftShowAvatarMapping[animaName] && studentManager != null)
        {
            if(sd != null){
                // 查找礼物预制体中的头像位置
                string avatarPath = giftAvatarPathMapping[animaName];
                Transform avatarTransform = giftInstance.transform.Find(avatarPath);
                if (avatarTransform == null)
                {
                    UnityEngine.Debug.LogWarning($"GiftManager: Avatar path '{avatarPath}' not found in gift prefab");
                    return;
                }
        
                // 获取头像组件
                Image avatarImage = avatarTransform.GetComponent<Image>();
                if (avatarImage == null)
                {
                 UnityEngine.Debug.LogWarning("GiftManager: Avatar Image component not found");
                    return;
                }
        
                // 设置头像
                string avatarUrl = sd.GetComponentInChildren<Student>().getAvatarUrl();
                ImageLoader.Instance.LoadImageFromUrl(avatarImage, avatarUrl);
            }
           
        }
    }
    
    // 在学生节点上播放礼物特效（针对F1点赞） -Done
    private void PlayGiftOnStudent(AnimaName animaName,GameObject sd = null)
    {
        if (sd == null)
        {
            UnityEngine.Debug.LogWarning("GiftManager: Failed to get random student node");
            return;
        }
        
        string giftPath = giftPathMapping[animaName];
        GameObject giftPrefab = Resources.Load<GameObject>(giftPath);
        
        if (giftPrefab == null)
        {
            UnityEngine.Debug.LogError($"GiftManager: Failed to load gift prefab at path {giftPath}");
            return;
        }
        
        // 实例化礼物预制体，直接添加到学生节点上
        GameObject giftInstance = Instantiate(giftPrefab, sd.transform);
        
        // 设置位置（根据需要调整）
        giftInstance.transform.localPosition = new Vector3(0, 50, 0); // 调整在学生上方显示
    }
    
    // 播放挑战类型礼物（针对F9挑战第一名）
    private void PlayChallengeGift(AnimaName animaName,GameObject sd = null)
    {
        // 获取第一名学生（假设是积分最高的学生）
        GameObject topStudent = GetTopStudent();
        if (topStudent == null)
        {
            UnityEngine.Debug.LogWarning("GiftManager: Failed to get top student");
            return;
        }
        
        // 获取挑战者
        if (sd == null)
        {
            UnityEngine.Debug.LogWarning("GiftManager: Failed to get challenger student");
            return;
        }
        
        string giftPath = giftPathMapping[animaName];
        GameObject giftPrefab = Resources.Load<GameObject>(giftPath);
        
        if (giftPrefab == null)
        {
            UnityEngine.Debug.LogError($"GiftManager: Failed to load gift prefab at path {giftPath}");
            return;
        }
        
        // 实例化礼物预制体
        GameObject giftInstance = Instantiate(giftPrefab, canvas);
        
        // 设置位置（根据需要调整）
        giftInstance.transform.localPosition = Vector3.zero;
        
        // 设置两个头像
        SetChallengeAvatars(giftInstance, animaName, topStudent, sd);
    }
    
    // 获取积分最高的学生
    private GameObject GetTopStudent()
    {
        if (studentManager == null || studentManager.GetAllStudents().Count == 0)
        {
            return null;
        }
        
        List<GameObject> students = studentManager.GetAllStudents();
        
        // 按积分排序
        students.Sort((a, b) => {
            return b.GetComponentInChildren<Student>().getJifen().CompareTo(a.GetComponentInChildren<Student>().getJifen());
        });
        
        // 返回积分最高的学生
        return students[0];
    }
    
    // 设置挑战礼物的两个头像
    private void SetChallengeAvatars(GameObject giftInstance, AnimaName animaName, GameObject topStudent, GameObject challengerStudent)
    {
        // // 设置第一名头像
        // if (topStudent != null)
        // {
        //     Student topStudentComponent = topStudent.GetComponentInChildren<Student>();
        //     if (topStudentComponent != null)
        //     {
        //         // 查找第一名头像位置
        //         string avatarPath = giftAvatarPathMapping[keyCode];
        //         Transform avatarTransform = giftInstance.transform.Find(avatarPath);
        //         if (avatarTransform != null)
        //         {
        //             Image avatarImage = avatarTransform.GetComponent<Image>();
        //             if (avatarImage != null)
        //             {
        //                 ImageLoader.Instance.LoadImageFromUrl(avatarImage, topStudentComponent.getAvatarUrl());
        //                 avatarTransform.gameObject.SetActive(true);
        //             }
        //         }
        //     }
        // }
        
        // 设置挑战者头像
        if (challengerStudent != null)
        {
            Student challengerStudentComponent = challengerStudent.GetComponentInChildren<Student>();
            if (challengerStudentComponent != null)
            {
                string avatarPath = giftAvatarPathMapping[animaName];
                // 查找挑战者头像位置
                Transform avatarTransform = giftInstance.transform.Find(avatarPath);
                if (avatarTransform != null)
                {
                    Image avatarImage = avatarTransform.GetComponent<Image>();
                    if (avatarImage != null)
                    {
                        ImageLoader.Instance.LoadImageFromUrl(avatarImage, challengerStudentComponent.getAvatarUrl());
                        avatarTransform.gameObject.SetActive(true);
                    }
                }
            }
        }
    }
    
}
